package net.neptech.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
/**
 * @Author HuangZhengmin
 * @desc  非问诊响应节点 - 处理非医疗咨询类请求
 * @Date 2025/8/19 17:43
 * @Version 1.0
 */
@Component
public class NonConsultResponseNode implements NodeAction {
  private static final Logger logger = LoggerFactory.getLogger(NonConsultResponseNode.class);

  private final ApplicationContext applicationContext;

  @Autowired
  public NonConsultResponseNode(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  private ChatClient getChatClient() {
    return applicationContext.getBean(ChatClient.class);
  }

  @Override
  public Map<String, Object> apply(OverAllState state) {
    logger.info("进入非问诊响应节点");
    try {
      ChatClient chatClient = getChatClient();
      if (chatClient == null) {
        throw new IllegalStateException("ChatClient is not available");
      }
    Map<String, Object> result = new HashMap<>();

    // 获取用户输入
    String userInput = (String) state.value("input").orElse("");

    // 生成非问诊响应
    String prompt = String.format(
            "用户输入: %s\n" +
                    "这是非医疗咨询类请求，请礼貌回应。" +
                    "如果需要医疗帮助，请引导用户描述具体症状。", userInput);

    String response = chatClient.prompt()
            .user(prompt)
            .call()
            .content();

    // 更新状态
    result.put("non_consult_response", response);
    result.put("final_recommendation", response);

    logger.info("非问诊请求已响应");
    return result;
  } catch (Exception e) {
      logger.error("非问诊响应节点处理失败", e);
      throw new RuntimeException("非问诊响应节点处理失败", e);
    }
}}
